package org.fixies.sample;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class SampleProduct {

    private int id;

    private String name;

    private int price;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    @Override
    public String toString() {
        String str =
                "id=[" + id + "]" + "name=[" + name + "]" + "price=[" + price + "]";
        return str;
    }

    public int insert(Connection conn) throws SQLException {
        String sql = "INSERT INTO PRODUCT VALUES (?,?,?)";
        PreparedStatement ps = conn.prepareStatement(sql);
        int i = 1;
        ps.setObject(i++, id);
        ps.setObject(i++, name);
        ps.setObject(i++, price);
        return ps.executeUpdate();
    }

    public static SampleProduct select(int id, Connection conn) throws SQLException {
        String sql = "SELECT ID, NAME, PRICE FROM PRODUCT WHERE ID=?";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setObject(1, id);
        ResultSet rs = ps.executeQuery();
        SampleProduct product = new SampleProduct();
        rs.next();
        product.id = rs.getInt("ID");
        product.name = rs.getString("NAME");
        product.price = rs.getInt("PRICE");
        rs.close();
        return product;
    }


    public int update(Connection conn) throws SQLException {
        String sql = "UPDATE PRODUCT SET NAME=?, PRICE=? WHERE ID=?";
        PreparedStatement ps = conn.prepareStatement(sql);
        int i = 1;
        ps.setObject(i++, name);
        ps.setObject(i++, price);
        ps.setObject(i++, id);
        return ps.executeUpdate();
    }

    public int delete(Connection conn) throws SQLException {
        String sql = "DELETE FROM PRODUCT WHERE ID=?";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setObject(1, id);
        return ps.executeUpdate();
    }
}
